import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../utils/http_helper.dart';
import '../screens/home/model/home_banner_model.dart';

// 分类数据状态类
class DiscoverCategoryState {
  final List<String> categories;
  final bool isLoading;
  final String? error;

  const DiscoverCategoryState({
    this.categories = const ['All'],
    this.isLoading = false,
    this.error,
  });

  DiscoverCategoryState copyWith({
    List<String>? categories,
    bool? isLoading,
    String? error,
  }) {
    return DiscoverCategoryState(
      categories: categories ?? this.categories,
      isLoading: isLoading ?? this.isLoading,
      error: error,
    );
  }
}

// 分类数据 Notifier
class DiscoverCategoryNotifier extends StateNotifier<DiscoverCategoryState> {
  DiscoverCategoryNotifier() : super(const DiscoverCategoryState()) {
    loadCategories();
  }

  Future<void> loadCategories() async {
    state = state.copyWith(isLoading: true, error: null);
    
    try {
      final userResponse = await HttpUtil().getModel<List<HomeBannerModel>>(
        'Comic/GetComicCategoriesList',
        fromJson: (json) => (json as List)
            .map((item) => HomeBannerModel.fromJson(item))
            .toList(),
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        final banners = userResponse!.result!;
        // 过滤type为0的数据
        final filteredBanners =
            banners.where((banner) => banner.type == 0).toList();

        // 提取分类名称
        final categoryNames = filteredBanners
            .map((banner) => banner.title ?? 'Unknown')
            .toList();

        // 保持All选项在第一位，然后添加从API获取的分类
        final allCategories = ['All', ...categoryNames];
        
        state = state.copyWith(
          categories: allCategories,
          isLoading: false,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: '获取分类失败',
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: '获取分类出错: $e',
      );
    }
  }

  void retry() {
    loadCategories();
  }
}

// Provider 定义
final discoverCategoryProvider = StateNotifierProvider<DiscoverCategoryNotifier, DiscoverCategoryState>(
  (ref) => DiscoverCategoryNotifier(),
);

// 过滤状态 Provider
final selectedStatusProvider = StateProvider<String>((ref) => 'All');
final selectedTypeProvider = StateProvider<String>((ref) => 'All');